package com.banksoft.cps.service.impl;

import com.banksoft.cps.bean.Device;
import com.banksoft.cps.bean.LoraValueJjll;
import com.banksoft.cps.bean.MonitorProduct;
import com.banksoft.cps.bean.lora.LoraData;
import com.banksoft.cps.bean.lora.LoraValue;
import com.banksoft.cps.bean.lora.LoraValueType;
import com.banksoft.cps.dao.DeviceDao;
import com.banksoft.cps.dao.LoraValueJjllDao;
import com.banksoft.cps.dao.MonitorProductDao;
import com.banksoft.cps.service.LoraDataService;
import com.banksoft.cps.util.UUIDFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by rongzhao.zhu on 2018/9/12.
 */
@Service
public class LoraDataServiceImpl implements LoraDataService {
    @Autowired
    LoraValueJjllDao loraValueJjllDao;
    @Autowired
    MonitorProductDao monitorProductDao;
    @Autowired
    DeviceDao deviceDao;
    @Override
    public void handle(LoraData loraData) {
        List<LoraValue> loraValues =  loraData.getValues();
        MonitorProduct monitorProduct = null;
        Device device = null;
        try{
            device = deviceDao.findByDeveui(loraData.getDeveui());
            monitorProduct = monitorProductDao.findById(device.getProductId());
        }catch (Exception e){
            e.printStackTrace();
        }
        String ssll = "";
        String jjll = "";
        if(loraValues != null ){
            for(LoraValue loraValue:loraValues){
                if(LoraValueType.JLJLL.name().equals(loraValue.getType())){
                    LoraValueJjll bean  = new LoraValueJjll();
                    bean.setId(UUIDFactory.random());
                    bean.setCreateTime(System.currentTimeMillis());
                    bean.setDeveui(loraData.getDeveui());
                    if(monitorProduct !=null ){
                        bean.setModulus(monitorProduct.getModulus());
                    }
                    bean.setValue(loraValue.getValue());
                    loraValueJjllDao.insert(bean);
                    jjll = loraValue.getValue();
                }else if(LoraValueType.SSLL.name().equals(loraValue.getType())){
                    ssll  = loraValue.getValue();
                }
                deviceDao.updateByDeveui(loraData.getDeveui(),jjll,ssll,System.currentTimeMillis());
            }
        }

    }
}
